/**
 * Created by lwh on 2016/10/3.
 */
var app = angular.module('myApp', ['ui.bootstrap', 'services', 'monospaced.qrcode']);
angular.module('services', ['ngResource', 'ngCookies']);
app.value('globalVar', {
    accessToken: 'L0xgSLWWWVxL',
    // backendUrl: 'http://localhost:8080/api'
    backendUrl: '../maternity/api'
});
app.filter("trustUrl", ['$sce', function ($sce) {
    return function (recordingUrl) {
        return $sce.trustAsResourceUrl(recordingUrl);
    };
}]);
app.controller('profileCtrl', function ($scope, MaternityService, $http) {
    if (GetQueryString("mid") == null) {
        alert("无效月嫂");
        location.href = "no-matron.html";
        return;
    }
    $scope.back = function () {
        history.back();
    };
    $scope.mid = parseInt(GetQueryString("mid"));
    $scope.mobileUrl = location.href.replace("/matron_profile", "/mobile_matron_profile");
    MaternityService.getGradePoints({mid: $scope.mid}, function (result) {
        $scope.grade = new Array(result.data.length + 1);
        var totalPoint = 0;
        var gradeCount = 0;
        angular.forEach(result.data, function (grade) {
            $scope.grade[grade.p] = grade.n;
            totalPoint += (grade.p * grade.n);
            gradeCount += grade.n;
        });
        $scope.avgGrade = totalPoint / gradeCount;
    })
});

app.controller('baseInfoCtrl', function ($scope, MaternityService) {
    if (GetQueryString("mid") == null) {
        return;
    }
    $scope.mid = parseInt(GetQueryString("mid"));
    MaternityService.getBaseInfo({mid: $scope.mid}, function (result) {
        if (result.success) {
            $scope.info = result.data;
        } else {
            switch (result.code) {
                case 201:
                    alert(result.msg);
                    location.href = "no-matron.html";
            }
        }
    });
});

app.controller('certificateCtrl', function ($scope, MaternityService) {
    var mid = parseInt(GetQueryString("mid"));
    if (mid == null) {
        return;
    }
    MaternityService.getCertificates({mid: mid}, function (result) {
        if (result.success) {
            $scope.certificates = result.data;
        } else {
            switch (result.code) {
            }
        }
    })
});

app.controller('trainCtrl', function ($scope, TrainingService) {
    var mid = parseInt(GetQueryString("mid"));
    if (mid == null) {
        return;
    }
    TrainingService.getExamInfo({mid: mid}, function (result) {
        if (result.uid !== -1) {
            $scope.exams = result.scores;
        }
    });
    TrainingService.getPostHospitals({mid: mid}, function (result) {
        if (result.success === true) {
            $scope.postHospitals = result.data;
        }
    });
    TrainingService.getTrainingSubjects({mid:mid},function (result) {
        if (result.success === true) {
            $scope.trainingSubjects = result.data;
        }
    })
});

app.controller('nursingCtrl', function ($scope, $filter, MaternityService, RecordService) {
    var mid = parseInt(GetQueryString("mid"));
    if (mid == null) {
        return;
    }
    MaternityService.getNursingExp({mid: mid}, function (result) {
        if (result.success) {
            $scope.nursingExp = result.data;
        } else {
            switch (result.code) {
            }
        }
    });

    function getCurMonthRecords(year, month, callback) {
        RecordService.getRecordsByMonth({mid: mid, year: year, month: month}, function (result) {
            if (result.success) {
                $scope.records = null;
                $scope.record = null;
                $scope.preMonthStr = null;
                $scope.nextMonthStr = null;
                if (result.data != null) {
                    $scope.preMonthStr = result.data.pre_month;
                    $scope.nextMonthStr = result.data.next_month;
                    $scope.records = $filter('orderBy')(result.data.records, 'start');
                    angular.forEach($scope.records, function (record) {
                        record.start = new Date(record.start * 1000);
                        record.end = new Date(record.end * 1000);
                        record.create_date = new Date(record.create_date * 1000);
                    });
                    callback();
                }
                getNextMonthRecords($scope.year, $scope.month);
            } else {
                switch (result.code) {

                }
            }
        });
    }

    function getNextMonthRecords(year, month) {
        RecordService.getRecordsByMonth({mid: mid, year: year, month: month + 1}, function (result) {
            if (result.success) {
                $scope.nextMonthRecords = null;
                if (result.data != null) {
                    $scope.nextMonthRecords = $filter('orderBy')(result.data.records, 'start');
                    angular.forEach($scope.nextMonthRecords, function (record) {
                        record.start = new Date(record.start * 1000);
                        record.end = new Date(record.end * 1000);
                        record.create_date = new Date(record.create_date * 1000);
                    });
                }
            } else {
                switch (result.code) {

                }
            }
        });
    }

    getCurMonthRecords(-1, -1, function () {
        if ($scope.records.length > 0) {
            $scope.record = $scope.records[$scope.records.length - 1];
            if ($scope.year != $scope.record.start.getFullYear()) {
                $scope.year = $scope.record.start.getFullYear();
                updateServingMonth();
            }
            $scope.month = $scope.record.start.getMonth();
            updateCalendar();
        }
    });

    $scope.preRecord = function () {
        var index = $scope.records.indexOf($scope.record);
        if (index < 0)
            return;
        if (index === 0) {
            if ($scope.preMonthStr == null)
                return;
            var yearMonth = $scope.preMonthStr.split(' ');
            $scope.yearToSelect = parseInt(yearMonth[0]);
            updateServingMonth();
            $scope.clickMonth(parseInt(yearMonth[1]));
        } else {
            var record = $scope.records[index - 1];
            var year = parseInt(record.start.getFullYear());
            var month = parseInt(record.start.getMonth());
            if (year === $scope.record.start.getFullYear() && month === $scope.record.start.getMonth()) {
                $scope.record = record;
                updateCalendar();
            }
            else {
                $scope.year = year;
                $scope.yearToSelect = year;
                updateServingMonth();
                $scope.month = month;
                getCurMonthRecords(year, month, function () {
                    $scope.record = $scope.records[$scope.records.length - 1];
                    updateCalendar();
                })
            }
        }
    };

    $scope.nextRecord = function () {
        var index = $scope.records.indexOf($scope.record);
        if (index < 0)
            return;
        if (index === $scope.records.length - 1) {
            if ($scope.nextMonthStr == null)
                return;
            var yearMonth = $scope.nextMonthStr.split(' ');
            $scope.yearToSelect = parseInt(yearMonth[0]);
            updateServingMonth();
            $scope.clickMonth(parseInt(yearMonth[1]));
        } else {
            var record = $scope.records[index + 1];
            var year = parseInt(record.start.getFullYear());
            var month = parseInt(record.start.getMonth());
            if (year === $scope.record.start.getFullYear() && month === $scope.record.start.getMonth()) {
                $scope.record = record;
            }
            else {
                $scope.year = year;
                $scope.yearToSelect = year;
                updateServingMonth();
                $scope.month = month;
                getCurMonthRecords(year, month, function () {
                    $scope.record = $scope.records[$scope.records.length - 1];
                })
            }
        }
    };


    // 日历配置
    $scope.today = new Date();
    $scope.today.setHours(0, 0, 0, 0);
    $scope.year = $scope.today.getFullYear();
    $scope.yearToSelect = $scope.today.getFullYear();
    $scope.month = $scope.today.getMonth();
    updateServingMonth();
    updateCalendar();
    function updateCalendar() {
        $scope.selectedMonthCalendar = getCalendar($scope.year, $scope.month);
        $scope.nextMonthCalendar = getCalendar($scope.year, $scope.month + 1);
    }

    function updateServingMonth() {
        RecordService.getServingMonthsInYear({mid: mid, year: $scope.yearToSelect}, function (result) {
            $scope.servingMonths = result.data;
        });
    }

    $scope.clickMonth = function (month) {
        $scope.month = month;
        $scope.year = $scope.yearToSelect;
        getCurMonthRecords($scope.year, month, function () {
            if ($scope.records != null) {
                if ($scope.records.length > 0)
                    $scope.record = $scope.records[$scope.records.length - 1];
                for (var i = 0; i < $scope.records.length; i++) {
                    var record = $scope.records[i];
                    if (record.start.getFullYear() === $scope.year && record.start.getMonth() === $scope.month) {
                        $scope.record = record;
                        break
                    }
                }
            }
        });
        updateCalendar();
    };
    $scope.preYear = function () {
        $scope.yearToSelect--;
        updateServingMonth();
    };
    $scope.nextYear = function () {
        if ($scope.yearToSelect < $scope.today.getFullYear()) {
            $scope.yearToSelect++;
            updateServingMonth();
        }
    };
    $scope.isToday = function (date) {
        return date.getTime() === $scope.today.getTime();
    };
    $scope.inSelectedMonth = function (date) {
        return date.getFullYear() === $scope.year && date.getMonth() === $scope.month;
    };
    $scope.inNextMonth = function (date) {
        return date.getFullYear() === $scope.year + Math.floor(($scope.month + 1) / 12) && date.getMonth() === ($scope.month + 1) % 12;
    };
    $scope.isServeDay = function (date) {
        if ($scope.records != null) {
            for (var i = 0; i < $scope.records.length; i++) {
                var record = $scope.records[i];
                if (record.start.getTime() <= date.getTime() && date.getTime() <= record.end.getTime())
                    return true;
            }
        }
        if ($scope.nextMonthRecords != null) {
            for (var i = 0; i < $scope.nextMonthRecords.length; i++) {
                var record = $scope.nextMonthRecords[i];
                if (record.start.getTime() <= date.getTime() && date.getTime() <= record.end.getTime())
                    return true;
            }
            return false;
        }
        else
            return false;
    };
    $scope.isActive = function (date) {
        if ($scope.record != null)
            return $scope.record.start.getTime() <= date.getTime() && date.getTime() <= $scope.record.end.getTime()
        else
            return false;
    };
    $scope.onDateClick = function (date) {
        if (!$scope.isServeDay(date) || $scope.isActive(date)) {
            return;
        }
        else {
            if ($scope.records != null) {
                for (var i = 0; i < $scope.records.length; i++) {
                    var record = $scope.records[i];
                    if (record.start.getTime() <= date.getTime() && date.getTime() <= record.end.getTime()) {
                        var year = parseInt(record.start.getFullYear());
                        var month = parseInt(record.start.getMonth());
                        if (year === $scope.record.start.getFullYear() && month === $scope.record.start.getMonth()) {
                            $scope.record = record;
                        }
                        else {
                            $scope.year = year;
                            $scope.yearToSelect = year;
                            updateServingMonth();
                            $scope.month = month;
                            getCurMonthRecords(year, month, function () {
                                $scope.record = $scope.records[$scope.records.length - 1];
                            })
                        }
                        updateCalendar();
                        return;
                    }
                }
            }
            if ($scope.nextMonthRecords != null) {
                for (var i = 0; i < $scope.nextMonthRecords.length; i++) {
                    var record = $scope.nextMonthRecords[i];
                    if (record.start.getTime() <= date.getTime() && date.getTime() <= record.end.getTime()) {
                        var year = parseInt(record.start.getFullYear());
                        var month = parseInt(record.start.getMonth());
                        $scope.year = year;
                        $scope.yearToSelect = year;
                        updateServingMonth();
                        $scope.month = month;
                        getCurMonthRecords(year, month, function () {
                            $scope.record = $scope.records[$scope.records.length - 1];
                        });
                        updateCalendar()
                        return;
                    }
                }
            }
        }
    };
    function getCalendar(year, month) {
        var firstDayInMonth = new Date(year, month, 1);
        var firstDayInFirstWeek = new Date(year, month, 1 - firstDayInMonth.getDay());
        var lastDayInMonth = new Date(year, month + 1, 0);
        var totalDay = firstDayInMonth.getDay() + lastDayInMonth.getDate() + 6 - lastDayInMonth.getDay();
        var dates = new Array(totalDay / 7);
        for (var i = 0; i < dates.length; i++) {
            dates[i] = new Array(7);
        }
        for (var j = 0; j < totalDay; j++) {
            dates[Math.floor(j / 7)][j % 7] = new Date(firstDayInFirstWeek.getFullYear(), firstDayInFirstWeek.getMonth(), firstDayInFirstWeek.getDate() + j);
        }
        return dates;
    }

    // 日历配置结束
});

app.controller('workingPhotoCtrl', function ($scope, MaternityService) {
    var mid = parseInt(GetQueryString("mid"));
    if (mid == null) {
        return;
    }
    MaternityService.getWorkingPhoto({mid: mid}, function (result) {
        if (result.success) {
            $scope.photos = result.data;
        } else {
            switch (result.code) {
            }
        }
    })
});